<?php

namespace WxWorkSDK\Member;

use WxWorkSDK\Error\Error;
use WxWorkSDK\Http\Http;
use WxWorkSDK\Result;

/**
 * Class OAuth2
 * https://work.weixin.qq.com/api/doc?st=1B0A53760B7C27B13B6946BE53DCE20E97EAD0B1D871121006555E08CA4B2C07EDDA84D37475720425DC146313416188345F673BE1879F8FAD4BCC91837D81E1F4C3A5FCCF853688857B943E5B94BFA0D0B4FA02349CEFE5C8F70FA1E0824FE0EAE00378A31FB6D49AEE514511473E8DBC153719D4AAB3934AB2FC617BBB63E0&vid=1688852493361401&cst=638927E403922786B83B6D9A9288B6889DC23170EDC182A1634A95D560D0B654C2A62F749A06A5AD6D11F0F1A40DAFCE&deviceid=01b22e36-adeb-48bf-9391-db5a9906e2c4&version=2.6.1.1329&platform=win#90000/90135/91335
 */
class OAuth2
{
    /**
     * 构造网页授权链接
     * @param  string  $appid
     * @param  string  $redirectUri
     * @param  string  $state
     * @return string
     * @Author wm
     * @Date   2018/12/19
     * @Time   17:00
     */
    public static function buildAuthUrl(string $appid, string $redirectUri, string $state = ''): string
    {
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid;
        $url .= '&redirect_uri='.urlencode($redirectUri);
        $url .= '&response_type=code';
        $url .= '&scope=snsapi_base';
        $url .= '&state='.$state;
        $url .= '#wechat_redirect';
        return $url;
    }

    /**
     * @param  string  $accessToken
     * @param  string  $code
     * @return array
     * @Author wm
     * @Date   2018/12/20
     * @Time   10:34
     */
    public static function getUserInfo(string $accessToken, string $code): Result
    {
        $url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={$accessToken}&code={$code}";
        [$bool, $response] = Http::request('GET', $url);
        if (!$bool) {
            return $response;
        }
        $response = json_decode($response, true);
        if ($response['errcode'] == 0) {
            return new Result(true, 0, 'ok', $response);
        } else {
            return new Result(false, Error::WX_MISTAKE, $response['errcode'].':'.$response['errmsg']);
        }
    }

}